package config

import (
	"fmt"

	"gitee.com/tsingeye/FreeEhome/tools"
	"gitee.com/tsingeye/FreeEhome/tools/logs"
	"github.com/astaxie/beego"
)

const (
	TimeLayout = "2006-01-02 15:04:05" //时间格式同意模板
)

//HTTP接口返回状态码
const (
	EHomeSuccessOK                 int64 = 200 //请求成功
	EHomeClientBadRequest          int64 = 400 //客户端请求的语法错误
	EHomeServerError               int64 = 500 //服务器内部错误
	EHomeUDPReplyTimeout           int64 = 504 //EHome UDP回复超时
	EHomeHookReplySessionTimeout   int64 = 505 //Hook回复超时
	EHomeUserNotFound              int64 = 600 //用户不存在
	EHomeInvalidToken              int64 = 601 //无效的token
	EHomeDeviceIDNotFound          int64 = 602 //设备ID不存在
	EHomeDeviceOffline             int64 = 603 //设备离线
	EHomeChannelIDNotFound         int64 = 604 //通道ID不存在
	EHomeGetSnapError              int64 = 605 //获取快照截图错误
	EHomeOnRecordMP4HookReplyError int64 = 606 //on_record_mp4录像回放hook错误
)

var (
	ServiceName                string //部署为服务器显示的名称
	TokenExpiresAt             int64  //token默认过期时间，单位秒，默认时间为3600
	EHomeUDPAddr               string //EHome UDP服务器地址
	OpenTimedScreenshot        bool   //是否开启定时截图，默认不开启
	TimedScreenshotPeriod      int64  //定时截图时间周期，默认6分钟
	EHomeAlarmUDPAddr          string //EHome报警UDP服务器地址，IP和Port需要和conf/config.xml中的Param中AlarmServerIP、AlarmServerUdpPort保持一致
	EHomeAlarmForwardRoute     string //EHome报警信息转发HTTP路由
	EHomeSinkIP                string //实时直播TCP推流IP
	EHomeSinkPort              int64  //实时直播TCP推流Port
	EHomeUpServerIP            string //录像列表播放配置IP
	EHomeUpServerPort          int64  //录像列表播放配置Port
	WaitEHomeReplyTime         int64  //发送请求，最长等待EHome客户端回复时间，默认3秒
	WaitHookOnPublishTimeout   int64  //发送请求，最长等待Hook触发on_publish返回session的时间，默认10秒。实时直播等待Hook触发时间
	WaitHookOnRecordMP4Timeout int64  //发送请求，最长等待Hook触发on_record_mp4返回session的时间，默认10秒。录像回放等待Hook触发时间
	WaitZLMReplyTime           int64  //zlm HTTP服务器超时回复时间，默认3秒
	EHomeAlarmForwardTimeout   int64  //EHome报警信息转发超时时间，默认3秒
	StreamIP                   string //IP和Port信息，用于组合合成流播放URL
	HLSPort                    string
	RTMPPort                   string
	RTSPPort                   string
	RedisAddr                  string           //Redis地址
	RedisPass                  string           //Redis密码
	ZLMGetSnapAddr             string           //zlm获取快照路由
	HTTPCodeMap                map[int64]string //初始化HTTP接口返回状态码
)

func init() {
	var err error

	//部署为服务器显示的名称
	ServiceName = beego.AppConfig.String("serviceName")
	if ServiceName == "" {
		ServiceName = "EHomeService"
		logs.BeeLogger.Error("init serviceName error, set default value: serviceName=%s", ServiceName)
	}

	TokenExpiresAt, err = beego.AppConfig.Int64("tokenExpiresAt")
	if err != nil {
		TokenExpiresAt = 3600
		logs.BeeLogger.Error("init tokenExpiresAt error, set default value: tokenExpiresAt=%d", TokenExpiresAt)
	}

	EHomeUDPAddr = beego.AppConfig.String("eHomeUDPAddr")
	if EHomeUDPAddr == "" {
		logs.PanicLogger.Panicln("init eHomeUDPAddr error, please check it!!!")
	}

	OpenTimedScreenshot, err = beego.AppConfig.Bool("openTimedScreenshot")
	if err != nil {
		OpenTimedScreenshot = false
		logs.BeeLogger.Error("init openTimedScreenshot error, set default value: openTimedScreenshot=%v", OpenTimedScreenshot)
	}

	TimedScreenshotPeriod, err = beego.AppConfig.Int64("timedScreenshotPeriod")
	if err != nil {
		TimedScreenshotPeriod = 6
		logs.BeeLogger.Error("init timedScreenshotPeriod error, set default value: timedScreenshotPeriod=%d", TimedScreenshotPeriod)
	}

	EHomeAlarmUDPAddr = beego.AppConfig.String("eHomeAlarmUDPAddr")
	if EHomeAlarmUDPAddr == "" {
		logs.PanicLogger.Panicln("init eHomeAlarmUDPAddr error, please check it!!!")
	}

	EHomeAlarmForwardRoute = beego.AppConfig.String("eHomeAlarmForwardRoute")
	if EHomeAlarmForwardRoute == "" {
		logs.PanicLogger.Panicln("init eHomeAlarmForwardRoute error, please check it!!!")
	}

	EHomeSinkIP = beego.AppConfig.String("eHomeSinkIP")
	if EHomeSinkIP == "" {
		logs.PanicLogger.Panicln("init eHomeSinkIP error, please check it!!!")
	}

	EHomeSinkPort, err = beego.AppConfig.Int64("eHomeSinkPort")
	if err != nil || EHomeSinkPort <= 0 {
		logs.PanicLogger.Panicln(fmt.Sprintf("init eHomeSinkPort error:%s, please check it!!!", err))
	}

	EHomeUpServerIP = beego.AppConfig.String("eHomeUpServerIP")
	if EHomeUpServerIP == "" {
		logs.PanicLogger.Panicln("init eHomeUpServerIP error, please check it!!!")
	}

	EHomeUpServerPort, err = beego.AppConfig.Int64("eHomeUpServerPort")
	if err != nil || EHomeUpServerPort <= 0 {
		logs.PanicLogger.Panicln(fmt.Sprintf("init eHomeUpServerPort error:%s, please check it!!!", err))
	}

	WaitEHomeReplyTime, err = beego.AppConfig.Int64("waitEHomeReplyTime")
	if err != nil || WaitEHomeReplyTime <= 0 {
		WaitEHomeReplyTime = 3
		logs.BeeLogger.Error("init waitEHomeReplyTime error, set default value: waitEHomeReplyTime=%d", WaitEHomeReplyTime)
	}

	WaitHookOnPublishTimeout, err = beego.AppConfig.Int64("waitHookOnPublishTimeout")
	if err != nil || WaitEHomeReplyTime <= 0 {
		WaitHookOnPublishTimeout = 10
		logs.BeeLogger.Error("init waitHookOnPublishTimeout error, set default value: waitHookOnPublishTimeout=%d", WaitHookOnPublishTimeout)
	}

	WaitHookOnRecordMP4Timeout, err = beego.AppConfig.Int64("waitHookOnRecordMP4Timeout")
	if err != nil || WaitEHomeReplyTime <= 0 {
		WaitHookOnRecordMP4Timeout = 10
		logs.BeeLogger.Error("init waitHookOnRecordMP4Timeout error, set default value: waitHookOnRecordMP4Timeout=%d", WaitHookOnRecordMP4Timeout)
	}

	WaitZLMReplyTime, err = beego.AppConfig.Int64("waitZLMReplyTime")
	if err != nil || WaitZLMReplyTime <= 0 {
		WaitZLMReplyTime = 3
		logs.BeeLogger.Error("init waitZLMReplyTime error, set default value: waitZLMReplyTime=%d", WaitZLMReplyTime)
	}

	EHomeAlarmForwardTimeout, err = beego.AppConfig.Int64("eHomeAlarmForwardTimeout")
	if err != nil || EHomeAlarmForwardTimeout <= 0 {
		EHomeAlarmForwardTimeout = 3
		logs.BeeLogger.Error("init eHomeAlarmForwardTimeout error, set default value: eHomeAlarmForwardTimeout=%d", EHomeAlarmForwardTimeout)
	}

	zlmSecret := beego.AppConfig.String("zlmSecret")

	getSnapTimeoutSec, err := beego.AppConfig.Int64("getSnapTimeoutSec")
	if err != nil || getSnapTimeoutSec <= 0 {
		getSnapTimeoutSec = 10
		logs.BeeLogger.Error("init getSnapTimeoutSec error, set default value: getSnapTimeoutSec=%d", getSnapTimeoutSec)
	}

	getSnapExpireSec, err := beego.AppConfig.Int64("getSnapExpireSec")
	if err != nil || getSnapExpireSec <= 0 {
		getSnapExpireSec = 30
		logs.BeeLogger.Error("init getSnapExpireSec error, set default value: getSnapExpireSec=%d", getSnapExpireSec)
	}

	streamIPList := beego.AppConfig.Strings("streamIP")
	hlsPortList := beego.AppConfig.Strings("hlsPort")
	rtmpPortList := beego.AppConfig.Strings("rtmpPort")
	rtspPortList := beego.AppConfig.Strings("rtspPort")
	switch len(streamIPList) {
	case 0:
		logs.PanicLogger.Panicln("init streamIP error, please check it!!!")
	case 1:
		StreamIP = streamIPList[0]

		switch len(hlsPortList) {
		case 0:
			logs.PanicLogger.Panicln("init hlsPort error, please check it!!!")
		default:
			HLSPort = hlsPortList[0]
		}

		switch len(rtmpPortList) {
		case 0:
			logs.PanicLogger.Panicln("init rtmpPort error, please check it!!!")
		default:
			RTMPPort = rtmpPortList[0]
		}

		switch len(rtspPortList) {
		case 0:
			logs.PanicLogger.Panicln("init rtspPort error, please check it!!!")
		default:
			RTSPPort = rtspPortList[0]
		}
	default:
		StreamIP = streamIPList[1]

		switch len(hlsPortList) >= 2 {
		case true:
			HLSPort = hlsPortList[1]
		default:
			logs.PanicLogger.Panicln("init hlsPort error, please check it!!!")
		}

		switch len(rtmpPortList) >= 2 {
		case true:
			RTMPPort = rtmpPortList[1]
		default:
			logs.PanicLogger.Panicln("init rtmpPort error, please check it!!!")
		}
		switch len(rtspPortList) >= 2 {
		case true:
			RTSPPort = rtspPortList[1]
		default:
			logs.PanicLogger.Panicln("init rtspPort error, please check it!!!")
		}
	}

	ZLMGetSnapAddr = fmt.Sprintf("http://%s:%s/index/api/getSnap?timeout_sec=%d&expire_sec=%d", streamIPList[0], hlsPortList[0], getSnapTimeoutSec, getSnapExpireSec)
	if zlmSecret != "" {
		ZLMGetSnapAddr = tools.StringsJoin(ZLMGetSnapAddr, "&secret=", zlmSecret)
	}

	RedisAddr = beego.AppConfig.String("redis::redisAddr")
	if RedisAddr == "" {
		logs.PanicLogger.Panicln("init redisAddr error, please check it!!!")
	}

	//只取值，无须判断
	RedisPass = beego.AppConfig.String("redis::redisPwd")
	// if RedisPass == "" {
	// 	logs.PanicLogger.Panicln("init redisPwd error, please check it!!!")
	// }

	//初始化HTTP接口返回状态码
	HTTPCodeMap = map[int64]string{
		EHomeSuccessOK:                 "OK",
		EHomeClientBadRequest:          "Bad Request",
		EHomeServerError:               "Server Error",
		EHomeUDPReplyTimeout:           "EHome UDP Reply Timeout",
		EHomeHookReplySessionTimeout:   "Hook Reply Session Timeout",
		EHomeUserNotFound:              "User Not Found",
		EHomeInvalidToken:              "Invalid Token",
		EHomeDeviceIDNotFound:          "DeviceID Not Found",
		EHomeDeviceOffline:             "Device Offline",
		EHomeChannelIDNotFound:         "ChannelID Not Found",
		EHomeGetSnapError:              "Get Snap Error",
		EHomeOnRecordMP4HookReplyError: "OnRecordMP4 Hook Reply Error",
	}
}
